package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save (@RequestBody DishDto dishDto) {

        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        return  R.success("新增菜品成功");
    }

    /**
     * 分页管理
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page (int page,int pageSize, String name) {

        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        LambdaQueryWrapper<Dish> queryWrapperWrapper = new LambdaQueryWrapper<>();

        queryWrapperWrapper.like(name!=null,Dish::getName,name);

        queryWrapperWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo,queryWrapperWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list = records.stream().map((item)->{

            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);

            return dishDto;
        }).collect(Collectors.toList());


        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get (@PathVariable Long id) {

        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }

    /**
     * 更改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update (@RequestBody DishDto dishDto) {

        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        return  R.success("新增菜品成功");
    }

//    /**
//     * 根据条件查询对应的菜品数据
//     * @param dish
//     * @return
//     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//
//        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
//        queryWrapper.eq(Dish::getStatus,1);
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//
//        List<Dish> list = dishService.list(queryWrapper);
//
//        return R.success(list);
//    }

    /**
     * 根据条件查询对应的菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = dishService.getByIdWithFlavor(item.getId());
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }

    /**
     * 菜品的起售和停售
     * @param status
     * @param ids
     * @return
     */

    @PostMapping("/status/{status}")
    public R<String> setStatus(@PathVariable int status,@RequestParam List<Long> ids) {

        //status 0停售，1起售，传过来0表示要把status修改为0；
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids != null,Dish::getId,ids);
        List<Dish> dishes = dishService.list(queryWrapper);
        //存储无法停售的菜品
        List<Dish> faultDishes = new ArrayList<>();
        //判断有无套餐包含此菜品，查setmealDish表
        LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
        for(Dish dish:dishes){
            queryWrapper1.clear(); // 清除之前的条件
            queryWrapper1.eq(SetmealDish::getDishId,dish.getId());
            if(setmealDishService.getOne(queryWrapper1) != null && status==0){
                faultDishes.add(dish);
            }
            else {
                dish.setStatus(status);
                dishService.updateById(dish);
            }
        }
        if (!faultDishes.isEmpty()) {
            // 拼接错误信息
            StringBuilder msgBuilder = new StringBuilder();
            int i = 0;
            for (Dish dish : faultDishes) {
                if (i != 0) {
                    msgBuilder.append('、');
                }
                msgBuilder.append(dish.getName());
                i++;
            }
            String msg = "菜品" + msgBuilder.toString() + "已在套餐中售卖，无法停售";
            return R.error(msg);
        }
        return R.success("菜品状态已经修改成功啦");
    }

    /**
     * 删除菜品
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> id){
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(id != null,Dish::getId,id);
        List<Dish> dishes = dishService.list(queryWrapper);
        //存储无法删除的菜品
        List<Dish> faultDishes = new ArrayList<>();
        //判断有无套餐包含此菜品，查setmealDish表
        LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
        for(Dish dish:dishes){
            queryWrapper1.clear(); // 清除之前的条件
            queryWrapper1.eq(SetmealDish::getDishId,dish.getId());
            if(setmealDishService.getOne(queryWrapper1) != null){
                faultDishes.add(dish);
            }
            else {
                dishService.removeById(dish);
            }
        }
        if (!faultDishes.isEmpty()) {
            // 拼接错误信息
            StringBuilder msgBuilder = new StringBuilder();
            int i = 0;
            for (Dish dish : faultDishes) {
                if (i != 0) {
                    msgBuilder.append('、');
                }
                msgBuilder.append(dish.getName());
                i++;
            }
            String msg = "菜品" + msgBuilder.toString() + "已在套餐中售卖，无法删除";
            return R.error(msg);
        }
        return R.success("菜品已经删除成功啦");
    }
}


